//
//  YQLTabBar.swift
//  YQL_WeiBo
//
//  Created by apple on 2016/11/12.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class YQLTabBar: UITabBar {

    
    var completeClosure: (() -> ())?
    
    //重新构造方法,添加中间的撰写按钮
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        //添加中间的撰写按钮
        addSubview(composeButton)
        
        composeButton.addTarget(self, action: #selector(clickComposebutton), for: .touchUpInside)
    }
    
    //撰写按钮的点击监听方法
    @objc private func clickComposebutton() {
        //设置为可选解包
        completeClosure?()
        print(#function,"撰写按钮被点击了")
    }
    
    //告诉使用者,这个类只能在村代码的环境中使用
    //在注销了自动报错后,手动添加按钮,并且添加按钮的点击事件后,使用者在Xib环境中也可以使用这个类
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        
        super.init(coder: aDecoder)
        //添加中间的撰写按钮
        addSubview(composeButton)
        
        composeButton.addTarget(self, action: #selector(clickComposebutton), for: .touchUpInside)
    }
    
    
    
    
    //懒加载中间的撰写按钮
    lazy var composeButton: UIButton = {
        //UIButton默认就是自定义
        let button = UIButton()
        
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        return button
    }()
    
    

    //重写布局方法设置按钮的Frame
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //计算button 的宽和高
        let width = UIScreen.main.bounds.width / 5
        let height = self.bounds.size.height
        //定义一个下标变量
        var index = 0
        //通过遍历tabBar的子控件找出4个按钮,重新设置4个按钮的Frame
        for subView in subviews{

            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subView.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)
                
                index += (index == 1 ? 2 : 1)
                
            }
        }
        
        //设置撰写按钮的Frame
//        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: height)
        
        //可以通过中心点和size来设置撰写按钮的位置
        composeButton.bounds.size = CGSize(width: width, height: height)
        composeButton.center = CGPoint(x: center.x, y: height * 0.5)
    }
    
    
    

}
